<template>
  <div class="home-page">
    <!-- 通知区域 - 一行显示 -->
    <div class="notification-section" v-if="announcements.length > 0 || announcementsLoading">
      <!-- 加载状态 -->
      <div v-if="announcementsLoading" class="notification-bar loading">
        <n-icon size="16" class="notification-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
            <path fill="currentColor" d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z" opacity=".25"/>
            <path fill="currentColor" d="M12,4a8,8,0,0,1,7.89,6.7A1.53,1.53,0,0,0,21.38,12h0a1.5,1.5,0,0,0,1.48-1.75,11,11,0,0,0-21.72,0A1.5,1.5,0,0,0,2.62,12h0a1.53,1.53,0,0,0,1.49-1.3A8,8,0,0,1,12,4Z">
              <animateTransform attributeName="transform" dur="0.75s" repeatCount="indefinite" type="rotate" values="0 12 12;360 12 12"/>
            </path>
          </svg>
        </n-icon>
        <span class="notification-text">加载通知中...</span>
      </div>

      <!-- 通知内容 - 一行显示 -->
      <div v-else-if="announcements.length > 0" class="notification-bar">
        <n-icon size="16" class="notification-icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
            <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
          </svg>
        </n-icon>
        <span class="notification-label">通知：</span>
        <span class="notification-content">
          {{ announcements[0].title }} - {{ announcements[0].brief }}
        </span>
        <span class="notification-date">{{ formatDate(announcements[0].publish_time) }}</span>
      </div>
    </div>

    <!-- 第一行：欢迎横幅和图片区域 -->
    <div class="top-section">
      <n-grid cols="1 s:1 m:1 l:2 xl:2 2xl:2" responsive="screen" :x-gap="16" :y-gap="16">
        <!-- 左侧：欢迎横幅 -->
        <n-grid-item>
          <div class="welcome-banner">
            <n-space vertical :size="12">
              <!-- 描述区域 -->
              <div class="banner-description-container">
                <n-text class="banner-description">
                 《三角洲行动》攻略站 | DFHUB.CN
www.dfhub.cn 为玩家提供游戏攻略、战术解析及数据参考，所有内容均基于玩家实测与官方公开信息。
接广告，有需要的联系QQ 1621535815  交流Q群：292182511
                </n-text>

                <!-- 快速链接 -->
                <div class="quick-links">
                  <n-button type="primary" size="medium" @click="router.push('/items')">
                    浏览物品列表
                    <template #icon>
                      <n-icon>
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                          <path fill="currentColor" d="M3 4h18v2H3V4zm0 7h12v2H3v-2zm0 7h18v2H3v-2z"/>
                        </svg>
                      </n-icon>
                    </template>
                  </n-button>
                  
                  <n-button type="info" size="medium" @click="router.push('/feature')">
                    功能请求与投票
                    <template #icon>
                      <n-icon>
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                          <path fill="currentColor" d="M18 13h-.68l-2 2h1.91L19 17H5l1.78-2h2.05l-2-2H6l-3 3v4c0 1.1.89 2 1.99 2H19a2 2 0 0 0 2-2v-4l-3-3zm-1-5.05l-4.95 4.95l-3.54-3.54l4.95-4.95L17 7.95zm-4.24-5.66L6.39 8.66a.996.996 0 0 0 0 1.41l4.95 4.95c.39.39 1.02.39 1.41 0l6.36-6.36a.996.996 0 0 0 0-1.41L14.16 2.3a.975.975 0 0 0-1.4.04z"/>
                        </svg>
                      </n-icon>
                    </template>
                  </n-button>
                </div>

                <!-- 重要声明 - 直接显示 -->
                <div class="banner-disclaimer">
                  <n-text strong class="disclaimer-title">免责声明：</n-text>
                  <n-space vertical :size="6" class="disclaimer-content">
                    <!-- 数据说明 -->
                    <n-text :depth="3" class="disclaimer-text">
                      本站攻略与游戏公开数据及玩家实测，仅供参考，请以游戏实际内容为准。
                    </n-text>
                    <n-text :depth="3" class="disclaimer-text">
                      涉及的游戏内货币（如哈夫币）价格均为模拟推算，非官方定价。
                    </n-text>
                    <!-- 版权声明 -->
                    <n-text :depth="3" class="disclaimer-text">
                      本站使用的游戏图片、素材等版权归腾讯公司所有，仅用于非商业性展示与玩家交流。
                    </n-text>
                    <n-text :depth="3" class="disclaimer-text">
                      若权利人认为存在侵权，请联系 QQ：1621535815，我们将立即处理或关停相关内容。
                    </n-text>
                    <!-- 安全提示 -->
                    <n-text :depth="3" class="disclaimer-text">
                      本站不涉及任何虚拟物品交易，请勿相信第三方交易信息，谨防诈骗。
                    </n-text>
                    <n-text :depth="3" class="disclaimer-text">
                      转载内容需标注来源「三角洲行动攻略站（www.dfhub.cn）」，禁止篡改后冒名发布。
                    </n-text>
                  </n-space>
                </div>
              </div>

            </n-space>
          </div>
        </n-grid-item>

        <!-- 右侧：图片区域 -->
        <n-grid-item>
          <div class="image-section">
            <!-- 图片展示区域 -->
            <div class="image-display">
              <div class="thumbnail-container" @click="showImageModal = true">
                <img 
                  src="@/assets/haozi.png" 
                  alt="图片展示" 
                  class="display-image thumbnail-image"
                  @error="handleImageError"
                  @load="handleImageLoad"
                />
                <!-- 放大图标提示 -->
                <div class="zoom-overlay">
                  <n-icon size="24" class="zoom-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                      <path fill="currentColor" d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5A6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5S14 7.01 14 9.5S11.99 14 9.5 14z"/>
                    </svg>
                  </n-icon>
                  <span class="zoom-text">点击放大</span>
                </div>
              </div>
            </div>
          </div>
        </n-grid-item>
      </n-grid>
    </div>

    <!-- 第二行：地图密码和数据概览 -->
    <div class="second-section">
      <div class="container">
        <n-grid cols="1 s:1 m:1 l:2 xl:2 2xl:2" responsive="screen" :x-gap="16" :y-gap="16">
          <!-- 左侧：地图密码 -->
          <n-grid-item>
            <n-card class="map-passwords-card" :bordered="true" size="small">
              <template #header>
                <div class="section-header">
                  <n-space align="center" :size="8">
                    <n-icon :size="20" color="#18a058">
                      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
                        <path fill="currentColor" d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12c5.16-1.26 9-6.45 9-12V5l-9-4z"/>
                      </svg>
                    </n-icon>
                    <n-text strong>地图密码</n-text>
                  </n-space>
                  <n-tag size="small" type="success">今日</n-tag>
                </div>
              </template>

              <!-- 密码卡片网格 -->
              <!-- 加载状态 -->
              <div v-if="loading.mapPasswords">
                <loading-skeleton type="card" :count="5" />
              </div>

              <!-- 实际内容 -->
              <div v-else-if="passwordsData.length > 0" class="map-password-grid">
                  <n-card
                    v-for="(password, index) in passwordsData"
                    :key="index"
                    size="small"
                    :bordered="false"
                    class="map-password-naive-card compact-card"
                    @click="copyPassword(password.value)"
                  >
                    <div class="map-card-content">
                      <div class="map-icon-container" :class="`map-icon-${index}`">
                        <n-icon size="20" class="map-icon">
                          <svg v-if="index === 0" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
                            <!-- 大坝 - 水坝图标 -->
                            <path fill="currentColor" d="M22 10V6c0-1.11-.89-2-2-2H4c-1.11 0-2 .89-2 2v4c0 1.11.89 2 2 2h2v2H2v2h4v2H4v2h16v-2h-2v-2h4v-2h-4v-2h2c1.11 0 2-.89 2-2M8 10H4V6h4v4m6 0h-4V6h4v4m6 0h-4V6h4v4z"/>
                          </svg>
                          <svg v-else-if="index === 1" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
                            <!-- 长工 - 工厂/工人图标 -->
                            <path fill="currentColor" d="M12 15c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3m9-12h-3V1h-3v2h-3V1H9v2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h15c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-6 5c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5"/>
                          </svg>
                          <svg v-else-if="index === 2" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
                            <!-- 巴克什 - 沙漠/山区图标 -->
                            <path fill="currentColor" d="M22.5 16.5h-1.77a9.27 9.27 0 0 1-3.18 3.18V22.5H14V20.4a7.17 7.17 0 0 1-4 0v2.1h-3.55v-2.82a9.27 9.27 0 0 1-3.18-3.18H1.5v-3.55h2.1a7.17 7.17 0 0 1 0-4H1.5V5.4h1.77A9.27 9.27 0 0 1 6.45 2.22V1.5H10v2.1a7.17 7.17 0 0 1 4 0V1.5h3.55v.72a9.27 9.27 0 0 1 3.18 3.18h1.77V9h-2.1a7.17 7.17 0 0 1 0 4h2.1Z"/>
                          </svg>
                          <svg v-else-if="index === 3" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
                            <!-- 航天 - 火箭图标 -->
                            <path fill="currentColor" d="M13.13 22.19L11.5 18.36c-1.15.29-2.35.43-3.5.43c0 0-4 0-9.5-5C1.63 16.53 4.79 19 8 19c1.33 0 2.69-.28 4-1c.28 1.23.89 2.08 1.13 2.19M14.5 6.5c0 .83-.67 1.5-1.5 1.5s-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5s1.5.67 1.5 1.5M20 13c-1.68 0-3.12-.85-3.7-2.55A4.62 4.62 0 0 0 18.5 9c0-2.76-2.24-5-5-5a4.62 4.62 0 0 0-1.45.23C13.75 3.07 14 1.73 14 .5c5 .5 9 5.06 9 9.5c0 2.42-.93 3-3 3m-7.05-6.5c.5-.5.5-1 0-1.5s-1-.5-1.5 0s-.5 1 0 1.5s1 .5 1.5 0M10.9 20.4L7.5 17c-5.06 2.84-5 5-5 5c.76 3 5 2.58 8.4-1.6Z"/>
                          </svg>
                          <svg v-else xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
                            <!-- 潮汐监狱 - 监狱/栅栏图标 -->
                            <path fill="currentColor" d="M4 9h16v11h-2v-9H6v9H4zm14 11h-2v-3h-2v3h-2v-3h-2v3H8v-3H6v3H4v2h16zm-7-19h2l-1-3l-1 3M4 4v3h2V5h12v2h2V4z"/>
                          </svg>
                        </n-icon>
                      </div>
                      <div class="map-info">
                        <div class="map-name">{{ password.label.replace(':', '') }}</div>
                        <div class="map-password-container">
                          <n-text :type="password.value ? 'primary' : 'secondary'" :strong="!!password.value" class="map-password-value">
                            {{ password.value || '暂无密码' }}
                          </n-text>
                          <n-tooltip v-if="password.value" trigger="hover" placement="bottom">
                            <template #trigger>
                              <n-icon size="16" class="copy-icon">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">
                                  <path fill="currentColor" d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
                                </svg>
                              </n-icon>
                            </template>
                            点击复制
                          </n-tooltip>
                        </div>
                      </div>
                    </div>
                  </n-card>
                </div>

              <!-- 空状态 -->
              <n-empty v-else description="暂无密码数据" size="small" />
            </n-card>
          </n-grid-item>

          <!-- 右侧：数据概览 -->
          <n-grid-item>
            <n-card class="stats-card" :bordered="true" size="small">
              <template #header>
                <div class="section-header">
                  <n-space align="center" :size="8">
                    <n-icon :size="20" color="#409eff">
                      <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
                        <path fill="currentColor" d="M3 3v18h18V3H3zm16 16H5V5h14v14zM7 12h2v5H7v-5zm4-3h2v8h-2V9zm4-3h2v11h-2V6z"/>
                      </svg>
                    </n-icon>
                    <n-text strong>数据概览</n-text>
                  </n-space>
                  <n-tag size="small" type="info">实时</n-tag>
                </div>
              </template>

              <!-- 统计数据卡片 -->
              <!-- 加载状态 -->
              <div v-if="loading.dashboard">
                <loading-skeleton type="card" :count="4" />
              </div>

              <!-- 实际内容 -->
              <div v-else class="stats-overview" style="display: flex; flex-direction: column; height: 100%;">
                  <!-- 上半部分：物品总数和活跃物品 -->
                  <div style="display: flex; gap: 8px; margin-bottom: 8px;">
                    <!-- 物品总数卡片 -->
                    <n-card size="small" :bordered="false" class="stats-naive-card compact-card" style="flex: 1;">
                      <div class="stats-card-content horizontal-layout" style="padding: 6px 8px;">
                        <span class="stats-card-title">物品总数：</span>
                        <n-text type="info" class="stats-value">{{ dashboardStats?.total_items || '0' }}</n-text>
                      </div>
                    </n-card>

                    <!-- 活跃物品卡片 -->
                    <n-card size="small" :bordered="false" class="stats-naive-card compact-card" style="flex: 1;">
                      <div class="stats-card-content horizontal-layout" style="padding: 6px 8px;">
                        <span class="stats-card-title">活跃物品：</span>
                        <n-text type="primary" class="stats-value">{{ activeItemsCount }}</n-text>
                      </div>
                    </n-card>
                  </div>

                  <!-- 中间部分：进度条 -->
                  <div style="margin-bottom: 8px;">
                    <div style="width: 100%; height: 12px; background-color: #f0f0f0; border-radius: 4px; overflow: hidden; display: flex; border: 1px solid #ddd; box-shadow: inset 0 1px 2px rgba(0,0,0,0.1); position: relative;">
                      <!-- 上涨部分 -->
                      <div :style="{
                        width: (risingProgressWidth || 0) + '%',
                        minWidth: risingProgressWidth > 0 ? '1px' : '0',
                        height: '100%',
                        backgroundColor: '#f56c6c',
                        transition: 'width 0.3s'
                      }"></div>
                      <!-- 下跌部分 -->
                      <div :style="{
                        width: (fallingProgressWidth || 0) + '%',
                        minWidth: fallingProgressWidth > 0 ? '1px' : '0',
                        height: '100%',
                        backgroundColor: '#67c23a',
                        transition: 'width 0.3s'
                      }"></div>
                    </div>
                  </div>

                  <!-- 下半部分：上涨和下跌 -->
                  <div style="display: flex; gap: 8px;">
                    <!-- 价格上涨卡片 -->
                    <n-card size="small" :bordered="false" class="stats-naive-card compact-card" style="flex: 1;">
                      <div class="stats-card-content horizontal-layout" style="padding: 6px 8px;">
                        <span class="stats-card-title">上涨：</span>
                        <div style="display: flex; align-items: center;">
                          <n-text type="error" class="stats-value">{{ dashboardStats?.price_rising || 0 }}</n-text>
                          <n-text type="error" style="font-size: 12px; margin-left: 4px;">({{ risingProgressWidth }}%)</n-text>
                        </div>
                      </div>
                    </n-card>

                    <!-- 价格下跌卡片 -->
                    <n-card size="small" :bordered="false" class="stats-naive-card compact-card" style="flex: 1;">
                      <div class="stats-card-content horizontal-layout" style="padding: 6px 8px;">
                        <span class="stats-card-title">下跌：</span>
                        <div style="display: flex; align-items: center;">
                          <n-text type="success" class="stats-value">{{ dashboardStats?.price_falling || 0 }}</n-text>
                          <n-text type="success" style="font-size: 12px; margin-left: 4px;">({{ fallingProgressWidth }}%)</n-text>
                        </div>
                      </div>
                    </n-card>
                  </div>
                </div>
            </n-card>
          </n-grid-item>
        </n-grid>
      </div>
    </div>

    <!-- 第三行：特勤处推荐和其他功能 -->
    <div class="third-section">
      <div class="container">
        <n-grid cols="1 s:1 m:1 l:2 xl:2 2xl:2" responsive="screen" :x-gap="16" :y-gap="16">
          <!-- 左侧：特勤处推荐 -->
          <n-grid-item>
            <special-operation-card />
          </n-grid-item>

          <!-- 右侧：排行榜 -->
          <n-grid-item>
            <ranking-card />
          </n-grid-item>
        </n-grid>
      </div>
    </div>

    <!-- 第四行：创作者信息 -->
    <div class="fourth-section">
      <div class="container">
        <n-grid cols="1 s:1 m:1 l:2 xl:2 2xl:2" responsive="screen" :x-gap="16" :y-gap="16">
          <!-- 左侧：推荐创作者 -->
          <n-grid-item>
            <creator-card />
          </n-grid-item>

          <!-- 右侧：创作者统计 -->
          <n-grid-item>
            <creator-stats-card />
          </n-grid-item>
        </n-grid>
      </div>
    </div>

    <!-- 第五行：子弹价格预测 -->
    <div class="fifth-section">
      <div class="container">
        <bullet-price-predict-card />
      </div>
    </div>

    <!-- 图片放大模态框 -->
    <n-modal
      v-model:show="showImageModal"
      preset="card"
      class="image-modal"
      :style="isMobile ? { width: '100%', height: '100%', margin: '0' } : { width: '95%', maxWidth: '1600px', marginTop: '2vh' }"
      :bordered="false"
      size="huge"
      :closable="true"
      :mask-closable="true"
      :auto-focus="false"
      transform-origin="center"
    >
      <div class="modal-image-container">
        <img
          src="@/assets/haozi.png"
          alt="图片预览"
          class="modal-image"
          @error="handleImageError"
          draggable="false"
        />
      </div>
    </n-modal>

    <!-- 首页更新日志弹窗 -->
    <n-modal
      v-model:show="showUpdateLogModal"
      preset="card"
      class="update-log-modal"
      :closable="true"
      :mask-closable="true"
      size="medium"
      style="max-width: 420px;"
      @after-leave="handleUpdateLogModalClose"
    >
      <template #header>
        <div style="display: flex; flex-direction: column; align-items: flex-start;">
          <span style="font-weight: bold; font-size: 18px;">更新日志</span>
          <span v-if="firstUpdateLog" style="font-size: 14px; color: #888; margin-top: 2px;">
            版本：{{ firstUpdateLog.version }} ｜ 日期：{{ firstUpdateLog.date }}
          </span>
        </div>
      </template>
      <div v-if="firstUpdateLog">
        <ul style="padding-left: 18px; margin: 0;">
          <li v-for="(item, idx) in firstUpdateLog.content" :key="idx">{{ item }}</li>
        </ul>
      </div>
      <div v-else>暂无更新日志内容</div>
      <!-- 弹窗底部说明和按钮 -->
      <div style="margin-top: 18px; display: flex; flex-direction: column; align-items: flex-start; gap: 8px;">
        <n-text depth="3" style="font-size: 13px;">关闭后3天内不再弹出</n-text>
        <n-button type="primary" size="small" @click="router.push('/update-log')">
          查看全部更新日志
        </n-button>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, computed, ref } from 'vue'
import { useRouter } from 'vue-router'

import { useStatsStore } from '@/stores/stats'
import { storeToRefs } from 'pinia'
import { getAnnouncements, type AnnouncementItem } from '@/api/announcements'
import { useMessage } from 'naive-ui'
import LoadingSkeleton from '@/components/common/LoadingSkeleton.vue'
import SpecialOperationCard from '@/components/home/SpecialOperationCard.vue'
import RankingCard from '@/components/home/RankingCard.vue'
import CreatorCard from '@/components/home/CreatorCard.vue'
import CreatorStatsCard from '@/components/home/CreatorStatsCard.vue'
import BulletPricePredictCard from '@/components/home/BulletPricePredictCard.vue'

// 静态导入本地更新日志 JSON 文件
import updateLogs from './update-log.json'

const router = useRouter()

const statsStore = useStatsStore()
const message = useMessage()

const {
  dashboardStats,
  mapPasswords,
  loading
} = storeToRefs(statsStore)

// 公告相关数据
const announcements = ref<AnnouncementItem[]>([])
const announcementsLoading = ref(false)

// 图片相关数据
const showImageModal = ref(false)
const imageLoading = ref(false)

// 移动端检测
const isMobile = computed(() => {
  if (typeof window === 'undefined') return false
  return window.innerWidth <= 768
})

// 地图密码数据
const passwordsData = computed(() => {
  if (!mapPasswords.value) return []

  return [
    { label: '大坝:', value: mapPasswords.value.daba },
    { label: '长工:', value: mapPasswords.value.changgong },
    { label: '巴克什:', value: mapPasswords.value.bakeshi },
    { label: '航天:', value: mapPasswords.value.hangtian },
    { label: '潮汐监狱:', value: mapPasswords.value.chaoxijianyu }
  ]
})

// 活跃物品数据计算
const activeItemsCount = computed(() => {
  const rising = Number(dashboardStats.value?.price_rising || 0)
  const falling = Number(dashboardStats.value?.price_falling || 0)
  return rising + falling
})

// 上涨进度条宽度
const risingProgressWidth = computed(() => {
  const rising = Number(dashboardStats.value?.price_rising || 0)
  const falling = Number(dashboardStats.value?.price_falling || 0)
  const total = rising + falling
  
  if (total === 0) return 0 // 如果没有数据，不显示进度条
  // 确保计算结果是数字而非字符串
  let width = Math.floor((rising / total) * 100) // 向下取整，避免总和超过100%
  console.log('上涨进度条宽度:', rising, '/', total, '=', width, '%', typeof width)
  return width
})

// 下跌进度条宽度
const fallingProgressWidth = computed(() => {
  const rising = Number(dashboardStats.value?.price_rising || 0)
  const falling = Number(dashboardStats.value?.price_falling || 0)
  const total = rising + falling
  
  if (total === 0) return 0 // 如果没有数据，不显示进度条
  // 确保总和为100%，将余数全部给下跌部分
  let width = 100 - risingProgressWidth.value
  console.log('下跌进度条宽度:', falling, '/', total, '=', width, '%', typeof width)
  return width
})

// 活跃物品百分比
const activeItemsPercentage = computed(() => {
  const total = Number(dashboardStats.value?.total_items || 0)
  if (total === 0) return 0
  return Math.min(Math.round((activeItemsCount.value / total) * 100), 100)
})

// 价格上涨百分比
const priceRisingPercentage = computed(() => {
  const total = Number(dashboardStats.value?.total_items || 0)
  if (total === 0) return 0
  const rising = Number(dashboardStats.value?.price_rising || 0)
  return Math.round((rising / total) * 100)
})

// 价格下跌百分比
const priceFallingPercentage = computed(() => {
  const total = Number(dashboardStats.value?.total_items || 0)
  if (total === 0) return 0
  const falling = Number(dashboardStats.value?.price_falling || 0)
  return Math.round((falling / total) * 100)
})

// 获取第一条更新日志内容，后续弹窗展示用
const firstUpdateLog = updateLogs && updateLogs.length > 0 ? updateLogs[0] : null // 类型自动推断

// 当前更新日志的 revision，用于判定弹窗是否需要重新显示
const currentRevision = (firstUpdateLog && typeof firstUpdateLog.revision === 'number') ? firstUpdateLog.revision : 0

// 复制密码功能
const copyPassword = async (password: string | number | null) => {
  if (!password) return

  try {
    await navigator.clipboard.writeText(String(password))
    
    // 显示成功提示
    showCopySuccess()
    console.log('密码已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    // 降级方案：使用传统方法复制
    const textArea = document.createElement('textarea')
    textArea.value = String(password)
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      // 显示成功提示
      showCopySuccess()
    } catch (execError) {
      console.error('降级复制方案也失败:', execError)
    }
    document.body.removeChild(textArea)
  }
}

// 显示复制成功的视觉反馈
const showCopySuccess = () => {
  // 使用 naive-ui 的消息提示
  message.success('密码已复制')
  
  // 添加动画效果
  const copyIcons = document.querySelectorAll('.copy-icon')
  copyIcons.forEach(icon => {
    icon.classList.add('copy-success')
    setTimeout(() => {
      icon.classList.remove('copy-success')
    }, 500)
  })
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  console.error('图片加载失败:', img.src)
  // 可以设置一个默认的占位图片
  img.style.display = 'none'
  // 显示错误提示
  message.error('图片加载失败')
}

// 处理图片加载完成
const handleImageLoad = () => {
  imageLoading.value = false
  console.log('图片加载完成')
}



// 获取公告数据
const fetchAnnouncements = async () => {
  try {
    announcementsLoading.value = true
    const response = await getAnnouncements({
      page: 1,
      pageSize: 5,
      sort: 'newest'
    })

    // 检查响应数据是否正确
    if (response && response.code === 1 && response.data && response.data.list) {
      announcements.value = response.data.list
    } else {
      console.warn('获取公告数据格式异常:', response)
      announcements.value = []
    }
  } catch (error) {
    console.error('获取公告失败:', error)
    announcements.value = []
  } finally {
    announcementsLoading.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    return '今天'
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }
}



// 弹窗显示状态
const showUpdateLogModal = ref(false) // 控制首页更新日志弹窗显示/隐藏

// 关闭首页更新日志弹窗时的处理函数
const handleUpdateLogModalClose = () => {
  // 关闭弹窗时，记录当前 revision
  localStorage.setItem('updateLogClosedRevision', currentRevision.toString()) // 保存本次关闭对应的 revision
  // 记录当前时间戳到 localStorage，单位毫秒
  localStorage.setItem('updateLogModalClosedAt', Date.now().toString())
  showUpdateLogModal.value = false // 关闭弹窗
}

// 页面加载时获取数据
onMounted(async () => {
  if (import.meta.env.DEV) {
    console.log('HomePage mounted, 开始获取数据...')
  }

  // 首页更新日志弹窗自动弹出逻辑
  try {
    // 从 localStorage 中读取上一次关闭时记录的 revision 和 时间戳
    const storedRevisionStr = localStorage.getItem('updateLogClosedRevision')
    const storedRevision = storedRevisionStr ? Number(storedRevisionStr) : null

    // 如果 revision 不一致，说明更新日志内容有改动 → 直接弹出
    if (storedRevision !== currentRevision) {
      showUpdateLogModal.value = true
    } else {
      // revision 一致，则继续按照 3 天冷却逻辑判断
      const closedAt = localStorage.getItem('updateLogModalClosedAt')
      const now = Date.now()
      const THREE_DAYS = 3 * 24 * 60 * 60 * 1000 // 259200000 毫秒

      // 没有关闭记录，或已超过 3 天，则弹出
      if (!closedAt || isNaN(Number(closedAt)) || now - Number(closedAt) > THREE_DAYS) {
        showUpdateLogModal.value = true
      }
    }
  } catch (e) {
    // Safari 隐私模式等可能导致 localStorage 读写异常，兜底直接弹出
    showUpdateLogModal.value = true
  }

  // 使用 requestIdleCallback 优化数据加载时机
  if ('requestIdleCallback' in window) {
    requestIdleCallback(() => {
      loadData()
    }, { timeout: 1000 })
  } else {
    // 降级方案：使用 setTimeout
    setTimeout(() => {
      loadData()
    }, 0)
  }
})

// 加载数据的函数
const loadData = async (retryCount = 0) => {
  try {
    // 优先加载关键数据，然后加载次要数据
    // 先加载统计数据（用户更关心）
    const statsPromise = statsStore.fetchAllStats()

    // 延迟加载公告数据（非关键）
    const announcementsPromise = new Promise(resolve => {
      setTimeout(async () => {
        try {
          await fetchAnnouncements()
          resolve(true)
        } catch (error) {
          resolve(false)
        }
      }, 100) // 延迟100ms加载公告
    })

    // 等待关键数据加载完成
    try {
      await statsPromise
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error('统计数据加载失败:', error)
      }
    }

    // 后台加载公告数据
    announcementsPromise.catch(error => {
      if (import.meta.env.DEV) {
        console.error('公告数据加载失败:', error)
      }
    })

    // 只在调试模式下输出数据获取完成信息
    if (import.meta.env.DEV) {
      console.log('📊 首页关键数据加载完成')
    }
  } catch (error) {
    console.error('数据获取失败:', error)

    // 如果失败且重试次数小于2，则尝试重试（减少重试次数）
    if (retryCount < 2) {
      if (import.meta.env.DEV) {
        console.log(`尝试重新加载数据 (${retryCount + 1}/2)...`)
      }
      // 延迟500ms后重试（减少重试延迟）
      setTimeout(() => {
        loadData(retryCount + 1)
      }, 500)
    }
  }
}
</script>

<style scoped>
/* 引入首页专用样式 */
@import '@/styles/components/home/HomePage.css';
</style>
